﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzWindows.Job
{
    sealed class RemoteToolsRun : IJob
    {
        log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(RemoteToolsRun));
        public void Execute(IJobExecutionContext context)
        {
            string returnMsg = string.Empty;
            //获取CMD命令
            string[] _CMDItems = System.Configuration.ConfigurationManager.AppSettings["CMDItems"].Split(';');
            foreach (var cmd in _CMDItems)
            {
                try
                {
                    RunCMDCommand(cmd, out returnMsg);
                    _logger.Info(returnMsg);
                }
                catch (Exception ex)
                {
                    _logger.Info(ex.Message);
                }
            }

        }

        private static string CMDPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";

        /// <summary>
        /// 执行CMD命令
        /// </summary>
        /// <param name="Command"></param>
        /// <param name="OutPut"></param>
        public static void RunCMDCommand(string Command, out string OutPut)
        {
            int msglength = -1;
            int P = 0;
            int count = 0;
            do
            {
                using (Process pc = new Process())
                {
                    Command = Command.Trim().TrimEnd('&') + "&exit";
                    pc.StartInfo.FileName = CMDPath;
                    pc.StartInfo.CreateNoWindow = true;
                    pc.StartInfo.RedirectStandardError = true;
                    pc.StartInfo.RedirectStandardInput = true;
                    pc.StartInfo.RedirectStandardOutput = true;
                    pc.StartInfo.UseShellExecute = false;
                    pc.OutputDataReceived += Pc_OutputDataReceived;
                    pc.ErrorDataReceived += Pc_ErrorDataReceived;
                    pc.Start();
                    //这两句别忘了，不然不会触发上面的事件   
                    //pc.BeginErrorReadLine();
                    //pc.BeginOutputReadLine();
                    pc.StandardInput.WriteLine(Command);
                    pc.StandardInput.AutoFlush = true;
                    OutPut = pc.StandardOutput.ReadToEnd();
                    Console.WriteLine(OutPut);
                    P = OutPut.IndexOf(Command) + Command.Length;
                    msglength = OutPut.Length - P - 3;
                    pc.WaitForExit();
                    pc.Close();
                }
                count++;
            } while (msglength < 0 && count < 10);
            if (msglength > 0)
                OutPut = OutPut.Substring(P, msglength);
            else
                OutPut = "无输出";
        }

        static string result = "";

        private static void Pc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            result += e.Data;
            Console.WriteLine(result);
        }

        private static void Pc_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            result += e.Data;
            Console.WriteLine(result);
        }
    }
}
